package com.liuzhengting.security.service.impl;

import com.liuzhengting.common.model.GeneralResult;
import com.liuzhengting.security.dao.SysUserMapper;
import com.liuzhengting.security.model.po.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired
	private SysUserMapper sysUserMapper;
	
	@Autowired
	private BCryptPasswordEncoder passwordEncoder;
	
	@Override
	public UserDetails loadUserByUsername(String loginname) throws UsernameNotFoundException {
		//需要构造出 org.springframework.security.core.userdetails.User 对象并返回
		if (loginname == null || "".equals(loginname)) {
			throw new RuntimeException("用户不能为空");
		}
		//根据用户名查询用户
		SysUser sysUser = sysUserMapper.selectByName(loginname);
		if (sysUser == null) {
			throw new RuntimeException("用户不存在");
		}
		
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		if (sysUser != null) {
			//获取该用户所拥有的权限
			// 声明用户授权
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ADMIN");
			grantedAuthorities.add(grantedAuthority);
		}

		return new User(sysUser.getLoginname(), sysUser.getPassword(), true, true, true, true, grantedAuthorities);
	}
}
